package com.mo.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class NioServerOptimize {

    public static void main(String[] args) throws IOException {
        List<SocketChannel> channelList = new ArrayList<>();
        ServerSocketChannel channel = ServerSocketChannel.open();
        channel.socket().bind(new InetSocketAddress(9000));
        //非阻塞IO
        channel.configureBlocking(false);

        Selector selector = Selector.open();
        //16路复用
        channel.register(selector, SelectionKey.OP_ACCEPT);

        System.out.println("服务启动成功！");
        //1.无数据让出CPU
        while (true) {
            //阻塞等待事件
            selector.select();
            //获取注册事件的所有示例
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator1 = selectionKeys.iterator();
            while (iterator1.hasNext()) {
                SelectionKey next = iterator1.next();
                if (next.isAcceptable()) {
                    ServerSocketChannel server = (ServerSocketChannel) next.channel();
                    SocketChannel socketChannel = server.accept();
                    socketChannel.configureBlocking(false);
                    //注册写事件
                    socketChannel.register(selector, SelectionKey.OP_READ);
                    System.out.println("连接成功！");
                } else if (next.isReadable()) {
                    SocketChannel server = (SocketChannel) next.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(128);
                    int len = server.read(buffer);
                    if (len > 0) {
                        System.out.println(new String(buffer.array()));
                    } else if (len == -1) {
                        System.out.println("客户端断开链接");
                        server.close();
                    }
                }
                iterator1.remove();

            }
        }
    }


}
